#include "main_ui.h"
#include "plugin/scenes/scenes.h"


#define FORCE_SHORT_POLL() \
  emberAfAddToCurrentAppTasks(EMBER_AF_FORCE_SHORT_POLL)

#define UNFORCE_SHORT_POLL() \
  emberAfRemoveFromCurrentAppTasks(EMBER_AF_FORCE_SHORT_POLL)

extern EmberEventControl emberAfPluginConnectionManagerPollEventControl;

static uint32_t timeModeSceneConfigStart = 0;

EmberEventControl evtSceneConf_EC;
void evtSceneConf_EF(void){

	emberEventControlSetInactive(evtSceneConf_EC);
	sceneConf_Stop();
}

int sceneConf_Start(void){

	if(emberAfNetworkState() != EMBER_JOINED_NETWORK)
		return -1;

	if(singleBlinkCtl_Ptn_ModeConfStart())
		return -1;


	emberEventControlSetDelayMS(evtSceneConf_EC, MUC_DURATION_LIMIT_SCENE_CONFIG);
	timeModeSceneConfigStart = halCommonGetInt32uMillisecondTick();

	if(emberEventControlGetActive(emberAfPluginConnectionManagerPollEventControl)){

	}else{
		FORCE_SHORT_POLL();
	}

	return 0;
}

int sceneConf_Stop(void){

	if(!emberEventControlGetActive(emberAfPluginConnectionManagerPollEventControl))
		UNFORCE_SHORT_POLL();

	emberEventControlSetInactive(evtSceneConf_EC);

	uint32_t curTick = halCommonGetInt32uMillisecondTick();
	uint32_t diffTick = curTick>=timeModeSceneConfigStart?
							(curTick-timeModeSceneConfigStart):
							(0xFFFFFFFF-timeModeSceneConfigStart+curTick);

	UTILS_PRINT(0, "Stop scene config, duration: %d ms.\n", diffTick);

	return singleBlinkCtl_Ptn_ModeConfStop();
}

void carelCallBack_PreAddScene(uint16_t groupId, uint8_t sceneId, uint8_t endpoint){

	UTILS_PRINT(0, "Invoke %s(), groupId: 0x%04X, sceneId: 0x%02X, ep: %d.\n",
			__func__, groupId, sceneId, endpoint);

	extern void emberAfGroupsClusterClearGroupTableCallback(uint8_t endpoint);
	extern EmberAfStatus carelSpy_AddEntryToGroupTable(uint8_t endpoint,
											uint16_t groupId, uint8_t *groupName);
	// Clear - Scene
	z3Ext_SceneTableClearByEndpoint(endpoint);
	// Clear - Group
	emberAfGroupsClusterClearGroupTableCallback(endpoint);
	// Create - Group
	carelSpy_AddEntryToGroupTable(endpoint, groupId, NULL);
	// Disable default response
	#define carel_emberAfFillCommandScenesClusterStoreSceneResponse(status, \
															  groupId, \
															  sceneId) \
	  emberAfFillExternalBuffer((ZCL_CLUSTER_SPECIFIC_COMMAND \
								 | ZCL_FRAME_CONTROL_SERVER_TO_CLIENT \
								 | ZCL_DISABLE_DEFAULT_RESPONSE_MASK), \
								ZCL_SCENES_CLUSTER_ID, \
								ZCL_STORE_SCENE_RESPONSE_COMMAND_ID, \
								"uvu", \
								status, \
								groupId, \
								sceneId);
	EmberAfClusterCommand *_cmd = emberAfCurrentCommand();
	emberAfSetCommandEndpoints(endpoint, _cmd->apsFrame->sourceEndpoint);
	carel_emberAfFillCommandScenesClusterStoreSceneResponse(0x00, groupId, sceneId);
	emberAfSendCommandUnicast(EMBER_OUTGOING_DIRECT, _cmd->source);
}


